import COS from 'cos-js-sdk-v5'

export interface UploadResult {
  Location: string
  ETag: string
  RequestId: string
  url: string
}

export interface UploadProgress {
  loaded: number
  total: number
  speed: number
  percent: number
}

/**
 * 生成随机的 COS 文件路径
 */
const generateCosKey = (filename: string): string => {
  const date = new Date()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const ymd = `${date.getFullYear()}${month < 10 ? `0${month}` : month}${day < 10 ? `0${day}` : day}`
  const randomSuffix = ('000000' + Math.floor(Math.random() * 1000000)).slice(-6)
  const ext = filename.substring(filename.lastIndexOf('.'))
  return `file/${ymd}/${ymd}_${randomSuffix}${ext}`
}

/**
 * 通用的 COS 上传函数
 * @param file 要上传的文件
 * @param onProgress 上传进度回调函数（可选）
 * @returns Promise<UploadResult> 包含 Location、ETag、RequestId 和 url 等信息
 */
export const cosUpload = async (
  file: File,
  onProgress?: (progress: UploadProgress) => void,
): Promise<UploadResult> => {
  const secretId = import.meta.env.VITE_COS_SECRET_ID
  const secretKey = import.meta.env.VITE_COS_SECRET_KEY
  const bucket = import.meta.env.VITE_COS_BUCKET
  const region = import.meta.env.VITE_COS_REGION
  const customDomain = import.meta.env.VITE_COS_CUSTOM_DOMAIN

  if (!secretId || !secretKey || !bucket || !region) {
    throw new Error('请配置完整的 COS 环境变量')
  }

  // 生成文件路径
  const key = generateCosKey(file.name)

  // 创建 COS 实例
  const cos = new COS({
    SecretId: secretId,
    SecretKey: secretKey,
  })

  // 上传文件
  return new Promise((resolve, reject) => {
    cos.uploadFile(
      {
        Bucket: bucket,
        Region: region,
        Key: key,
        Body: file,
        onProgress: (progressData) => {
          if (onProgress) {
            onProgress({
              loaded: progressData.loaded,
              total: progressData.total,
              speed: progressData.speed || 0,
              percent: Math.round(progressData.percent * 100),
            })
          }
        },
      },
      (err, data) => {
        if (err) {
          reject(new Error(`上传失败: ${err.message}`))
        } else {
          const url = customDomain ? `https://${customDomain}/${key}` : data.Location
          resolve({
            Location: data.Location,
            ETag: data.ETag,
            RequestId: data.RequestId || '',
            url: url,
          })
        }
      },
    )
  })
}
